import axios from 'axios'
import { message as ElMessage, loading as ElLoading } from '../tools/Toast.js'
class Http {
    get(url, data, headers, loading) {
        // 返回的是promise对象
        return this.instance(loading).get(url, {
            params: data,
            headers
        })
    }
    // post请求
    post(url, data, headers, loading) {
        // 返回的是promise对象
        return this.instance(loading).post(url, data, {
            headers
        })
    }

    put(url, data = {}, headers, loading) {
        data['_method'] = 'PUT';
        return this.instance(loading).post(url, data, {
            headers
        });
    }

    delete(url, data, headers, loading) {
        return this.instance(loading).delete(url, {
            params: data,
            headers
        })
    }

    instance(loading) {
        let ld = null;
        if (!loading) {
            ld = ElLoading({
                text: '请求中...',
                background: 'rgba(0, 0, 0, 0.7)'
            });
        }
        let instance = axios.create({
            baseURL: '', // 基础路径
            timeout: 5000,
        })
        instance.defaults.headers.post['Content-Type'] = 'application/x-www-`form-urlencoded;charset=UTF-8';
        instance.defaults.withCredentials = true;
        // 请求拦截
        instance.interceptors.request.use((config) => {
            let { headers } = config;
            // 在这里设置请求头
            let header = {
                'user-id': localStorage.getItem('id') || '',
                'token': localStorage.getItem('token') || ''
            }
            Object.assign(headers, header);
            return config;
        })
        // 响应拦截
        instance.interceptors.response.use((res) => {
            ld?.close();
            const { data } = res;
            // 存入token到本地
            res.headers['token'] && localStorage.setItem('token', res.headers['token']);
            res.headers['user-id'] && localStorage.setItem('userId', res.headers['user-id']);
            return Promise.resolve(data);
        }, (err) => {
            ld?.close();
            ElMessage({
                type: 'error',
                message: "网络错误"
            })
            return Promise.reject(err)
        })

        return instance
    }
}
export default new Http;